#include "StorageFuncCtr.h"
#include "utils/Defs.h"
#include <json/json.h>

using namespace drogon;

SNB_API_BEGIN

// 模板函数实现
template <typename T>
HttpResponsePtr StorageFuncCtr::createApiResponse(T&& result)
{
    if constexpr (std::is_same_v<std::decay_t<T>, Json::Value>) {
        return HttpResponse::newHttpJsonResponse(std::forward<T>(result));
    } else if constexpr (std::is_same_v<std::decay_t<T>, std::string>) {
        auto resp = HttpResponse::newHttpResponse();
        resp->setBody(std::forward<T>(result));
        return resp;
    } else {
        LOG_ERROR << "Unsupported response type";
        return HttpResponse::newHttpResponse(); // 防止编译警告
    }
}

// 处理函数实现
void StorageFuncCtr::handleHelloWorld(
    const HttpRequestPtr& req,
    std::function<void(const HttpResponsePtr&)>&& callback)
{
    callback(createApiResponse("Hello, Storage World!"));
}

void StorageFuncCtr::handleGetAllDiskInfo(
    const HttpRequestPtr& req,
    std::function<void(const HttpResponsePtr&)>&& callback)
{
    callback(createApiResponse(m_storageService->getAllDiskInfo()));
}

void StorageFuncCtr::handleGetAllDiskNames(
    const HttpRequestPtr& req,
    std::function<void(const HttpResponsePtr&)>&& callback)
{
    Json::Value response;
    response["diskNames"] = m_storageService->getAllDiskNames();
    callback(createApiResponse(response));
}

void StorageFuncCtr::handleGetAllDiskUuids(
    const HttpRequestPtr& req,
    std::function<void(const HttpResponsePtr&)>&& callback)
{
    Json::Value response;
    auto uuids = m_storageService->getAllDiskUuids();
    for (auto&& uuid : uuids) {
        response["diskUuids"].append(std::move(uuid));
    }
    callback(createApiResponse(response));
}

void StorageFuncCtr::handleGetDiskInfoByUuid(
    const HttpRequestPtr& req,
    std::function<void(const HttpResponsePtr&)>&& callback,
    const std::string& uuid)
{
    auto diskInfo = m_storageService->getDiskInfoByUuid(uuid);
    if (diskInfo.isNull()) {
        callback(HttpResponse::newNotFoundResponse());
        return; // 重要：返回避免继续执行
    }
    callback(createApiResponse(diskInfo));
}

void StorageFuncCtr::handleGetDiskStateByUuid(
    const HttpRequestPtr& req,
    std::function<void(const HttpResponsePtr&)>&& callback,
    const std::string& uuid)
{
    auto state = m_storageService->getDiskStateByUuid(uuid);
    if (state.empty()) {
        callback(HttpResponse::newNotFoundResponse());
        return; // 重要：返回避免继续执行
    }
    callback(createApiResponse(std::move(state)));
}

SNB_API_END